// MgoTest project main.go
package main

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"time"

	"gopkg.in/mgo.v2"
	//"gopkg.in/mgo.v2/bson"
)

type Person struct {
	UserName    string `bson:"name" json:"name"`
	Password    string `bson:"pwd" json:"pwd"`
	MobilePhone string `bson:"mobilePhone" json:"mobilePhone"`
	Sex         string `bson:"sex" json:"sex"`
}

const (
	URL = "127.0.0.1:27017"
)

func catchPanic() {
	if v := recover(); v != nil {
		fmt.Println("recover(), catch error :", v)
	}
}

func Test() {
	defer catchPanic()

	dial := mgo.DialInfo{
		Addrs:    []string{URL},
		Username: "auth01",
		Password: "auth01",
		Database: "testUsers",
		Timeout:  10 * time.Second}

	session, err := mgo.DialWithInfo(&dial)
	if err != nil {
		panic(err)
	}
	defer session.Close()

	session.SetMode(mgo.Monotonic, true)

	db := session.DB("testUsers") //数据库名称
	userTable := db.C("myUsers")  //如果该集合已经存在的话，则直接返回

	//*****集合中元素数目********
	countNum, err := userTable.Count()
	if err != nil {
		panic(err)
	}
	fmt.Println("Things objects count: ", countNum)

	//*******插入元素*******
	newUser := Person{
		MobilePhone: "18811577546",
		UserName:    "zhangzheHero",
		Password:    "hjklw!@34az",
		Sex:         "female"}

	//	//一次可以插入多个对象 插入两个Person对象
	psum := md5.New()
	psum.Write([]byte(newUser.MobilePhone + ":mongo:" + newUser.Password))
	newUser.Password = hex.EncodeToString(psum.Sum(nil))

	err = userTable.Insert(&newUser)
	if err != nil {
		panic(err)
	}

	//	//*****查询单条数据*******
	//	result := Person{}
	//	err = userTable.Find(bson.M{"phone": "456"}).One(&result)
	//	fmt.Println("Phone:", result.Name, result.Phone)

	//	//*****查询多条数据*******
	//	var personAll Men //存放结果
	//	iter := userTable.Find(nil).Iter()
	//	for iter.Next(&result) {
	//		fmt.Printf("Result: %v\n", result.Name)
	//		personAll.Persons = append(personAll.Persons, result)
	//	}

	//	//*******更新数据**********
	//	err = userTable.Update(bson.M{"name": "ccc"}, bson.M{"$set": bson.M{"name": "ddd"}})
	//	err = userTable.Update(bson.M{"name": "ddd"}, bson.M{"$set": bson.M{"phone": "12345678"}})
	//	err = userTable.Update(bson.M{"name": "aaa"}, bson.M{"phone": "1245", "name": "bbb"})

	//	//******删除数据************
	//	_, err = userTable.RemoveAll(bson.M{"name": "Ale"})
}

func main() {
	fmt.Println("Hello World!")

	Test()

	fmt.Println("END")
}
